iT邦幫忙

2024 iThome 鐵人賽

DAY 3
0
佛心分享-刷題不只是刷題

轉生理工組後從零開始的leetcode刷題系列 第 3

day-3[easy.2047]number of valid words in a sentence

  • 分享至 

  • xImage
  •  

A sentence consists of lowercase letters ('a' to 'z'), digits ('0' to '9'), hyphens ('-'), punctuation marks ('!', '.', and ','), and spaces (' ') only. Each sentence can be broken down into one or more tokens separated by one or more spaces ' '.

A token is a valid word if all three of the following are true:

It only contains lowercase letters, hyphens, and/or punctuation (no digits).
There is at most one hyphen '-'. If present, it must be surrounded by lowercase characters ("a-b" is valid, but "-ab" and "ab-" are not valid).
There is at most one punctuation mark. If present, it must be at the end of the token ("ab,", "cd!", and "." are valid, but "a!b" and "c.," are not valid).
Examples of valid words include "a-b.", "afad", "ba-c", "a!", and "!".

Given a string sentence, return the number of valid words in sentence.


一樣先把題目看不懂的部分拿去翻譯

  • valid =有效的
    題目大意就是依照規則區分單字是否有效,統計一共有幾個有效單字
    我的解題思路大致如下
    https://ithelp.ithome.com.tw/upload/images/20240917/20169432nzGxHBd8em.jpg

第二段的判別部分雖然繁瑣但比較簡單,所以先產出來了
public boolean isValid(String token ){
if (token.isEmpty()){
return false;
}
int hCount = 0;
int pCount = 0;
for (int i = 0; i<token.length();i++){
char c = token.charAt(i);

        if (Character.isDigit(c)){
            return false;
        }else if (c == '-'){
            hCount ++;
            if (hCount > 1 || i == 0 || i== token.length()-1
                    || !Character.isLowerCase(token.charAt(i-1))
                    || !Character.isLowerCase(token.charAt(i+1)) ){
                return false;
            }
        }else if (c =='!' || c =='.' || c ==','){
            pCount ++;
            if (pCount > 1 || i != token.length()-1){
                return false;
            }
        }else if (!Character.isLowerCase(c)){
            return false;
        }
    }
    return true;

不過我想很久都寫不出第一步,感覺沒有學過能夠拆解字串的語法,所以最終上網搜尋了一下...

  • sentence.trim():可以去除字串開頭與結尾的空格。
  • String token:String:元素類型 變量名 :可更迭之對象

然後出現了一個我從來沒聽過的詞----「正則表達式」!

  • 正則表達式:可以用來搜索、匹配、替換和操作文本。
    (舉例來說~
    a.b可以匹配 abc,a2c,a!c
    a+ 可以匹配 "a"、"aa"、"aaa" 等,但不匹配空字符串)
  • split():根據指定的正則表達式分割字符串。
  • 正則表達式“ \s+ ”:\s 代表任意空白字符;\s+ 可以匹配任意數量的空格

所以第一段程式就長這樣

public int countValidWords(String sentence){
//依照空格拆解出單字
//trim可刪除頭尾空白
//正則表達式\s+可匹配任意數量空格
int count = 0;
String[] wd = sentence.trim().split("\s+");

    for (String token : wd){
        if (isValid(token)){
            count++;
        }

    }
    return count;
}

丟去leetcode看結果!很愉快的成功下課!
https://ithelp.ithome.com.tw/upload/images/20240917/201694325AT6pJInFb.png
但由於今天是中秋節,所以先不精修程式了,嫦娥會原諒我的:P


上一篇
day-2 [easy.1929]concatenation of array
下一篇
day-4[easy.1812]determine color of a chessboard square
系列文
轉生理工組後從零開始的leetcode刷題30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言